package com.ruoyi.trigger.job;

import com.ruoyi.task.model.entity.TaskEntity;
import com.ruoyi.task.service.ITaskService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * TODO
 *
 * @Description
 * @Author wkm
 * @Date 2024/12/28
 **/
@Component()
@Slf4j
public class SendMessageTaskXxlJob {

    @Resource
    private ITaskService taskService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private ThreadPoolTaskExecutor executor;

    @XxlJob("XxlJob")
    public void exec(){
        log.info("Xxl-job定时任务调度");
        /** 加锁抢占 */
        RLock lock = redissonClient.getLock("Xxl-Job-SendMessage");
        boolean isLocked = false;
        try{
            isLocked = lock.tryLock(3,0, TimeUnit.SECONDS);
            if(!isLocked) return;
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            for(TaskEntity taskEntity : taskEntities){
                executor.execute(()->{
                    try {
                        taskService.sendMessage(taskEntity);
                        taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(),taskEntity.getMessageId());
                        log.info("Xxl-Job定时任务,发送MQ消息成功 userId :{} topic :{}",taskEntity.getUserId(),taskEntity.getTopic());
                    }catch (Exception e) {
                        log.error("定时任务,发送MQ消息失败 userId :{} topic :{}", taskEntity.getUserId(), taskEntity.getTopic());
                        taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                    }
                });
            }
        }catch (Exception e){
            log.error("定时任务,扫描MQ任务表失败",e);
        }finally {
            if (isLocked){
                lock.unlock();
            }
        }
    }
}
